用一個ImageView顯示顏色,和四個SeekBar分別代表R、G、B、A四個數值
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/imageView"
app:srcCompat="@android:color/transparent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="8dp"
android:layout_marginTop="8dp" android:layout_marginEnd="8dp"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintTop_toBottomOf="@+id/tv_color"
android:background="#000000"/>
<SeekBar
android:layout_width="0dp"
android:max="255"
android:layout_height="wrap_content"
android:id="@+id/seekBar_r" app:layout_constraintStart_toEndOf="@+id/textView2"
android:layout_marginStart="8dp"
app:layout_constraintTop_toTopOf="@+id/textView2"
app:layout_constraintBottom_toBottomOf="@+id/textView2"
app:layout_constraintEnd_toEndOf="@+id/seekBar_a"/>
fun setcolor(a: Int, r: Int, g: Int, b: Int) {
//a,r,g,b為外部變數(型別為Int)
val A = if(Integer.toHexString(a).length == 1) "0"+Integer.toHexString(a)else Integer.toHexString(a)
val R = if(Integer.toHexString(r).length == 1) "0"+Integer.toHexString(r) else Integer.toHexString(r)
val G = if(Integer.toHexString(g).length == 1) "0"+Integer.toHexString(g) else Integer.toHexString(g)
val B = if(Integer.toHexString(b).length == 1) "0"+Integer.toHexString(b) else Integer.toHexString(b)
}
使用setBackgroundColor()
設置ImageView的顏色
//將四個數值合成一個字串 並在最前面補上#
val color = "#" + A + R + G + B
imageView.setBackgroundColor(Color.parseColor(color))
tv_color.text = color
seekBar_a.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{})
有三個必須 override 的 funtion:
override fun onProgressChanged(seekbar: SeekBar, progress: Int, fromUser: Boolean){}
override fun onStartTrackingTouch (seekBar: SeekBar){}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
將設置顏色的function寫在onProgressChanged
seekBar_a.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(p0: SeekBar, p1: Int, p2: Boolean) {
//a為外部變數
a = p1
//將a的值用百分率顯示 表示顏色濃度
tv_a.text = format("%3d", a * 100 / 255) + "%"
setcolor(a, r, g, b)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
使用迴圈和Thread,可以做到類似呼吸燈的效果